//原生nodejs实现get请求

var http = require('http')
var fs = require('fs')
var url = require("url");
const path = require('path')
//异步读取描述符
fs.open('./static/1024.png', 'r' , (error, fd)=>{
	console.log('png-fd', fd)
})
//同步读取描述符
const fd= fs.openSync('./static/login.html', 'r')
console.log('html-fd', fd)
//异步读取文件属性
fs.stat('./static/1024.png', (error, stat)=>{
	if(error){
		console.log(error)
		return
	}
	//console.log('stat', stat)
})
//同步读取文件属性
const readAttr = fs.statSync('./static/login.html')
//console.log(readAttr)

//读取文件路径
const notes = './static/login.html'
console.log(path.dirname(notes))
console.log(path.basename(notes))
console.log(path.extname(notes))
//连接多个路径
const user = '/joe'
console.log(path.join('/user' + user + '/aa.txt'))
console.log(path.resolve('zqf.txt'))

//读写文件
fs.readFile('./static/login.html', 'utf8', (error, data) => {
	// console.log(data)
})
//默认覆盖文件内容，如果不存在则创建，可增加参数flag将内容插入到首尾
fs.writeFile('./static/test.txt', '这是写入的内容zqf',{flag: 'a+'}, error => {
	if(error){
		console.log(error)
		return
	}else{
		console.log('写入成功')
	}
})
//追加文件内容
fs.appendFile('./static/test.txt', 'yileng', error => {
	if(!error){
		console.log('追加成功')
	}
})
//判断、创建文件夹
const folderName = './static/zqf'
fs.access(folderName, (error, data)=>{
	if(!error){
		console.log('存在该文件夹')
	}
})
try{
	if(!fs.existsSync(folderName)){
		fs.mkdirSync(folderName)
	}
}catch (err) {
	console.log(err)
}




//创建http服务
http.createServer(function(req, res) {
	//console.log(req.url)
	//console.log(url.parse(req.url))
	let pathname = url.parse(req.url).pathname
 	switch (pathname) {
 		case '/home':
 			res.setHeader('Content-Type', 'application/json;charset=utf-8')
 			res.write('home页面')
 			res.end()
 			break;
 		case '/mine':
 			res.setHeader('Content-Type', 'application/json;charset=utf-8')
 			res.write('mine页面')
 			res.end()
 			break;
 		case '/login':
 			fs.readFile('./static/login.html', function(error, data) {
 				if (error) throw error
 				// res.write(data)
 				res.end('zqf123123')
 			})
 			break;
 		case '/1024.png':
 			fs.readFile('./static/1024.png', 'binary', function(error, data) {
 				if (error) throw error
 				res.write(data, 'binary')
 				res.end()
 			})
 			break;
 		default:
 			res.setHeader('Content-Type', 'application/json;charset=utf-8')
 			res.write('非法的路由')
 			res.end()
 			break;
 	}
}).listen(8000, function() {
 	console.log('服务器运行端口:8000')
})
